<template>
  <div class="leave-balance-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Calendar /></el-icon>
            <span class="header-title">{{ isHR ? '假期余额管理' : '我的假期余额' }}</span>
          </div>
          <div v-if="isHR" class="header-right">
            <el-button type="primary" @click="handleAddBalance">
              <el-icon><Plus /></el-icon>
              设置余额
            </el-button>
          </div>
        </div>
      </template>
      
      <div v-if="balanceList.length === 0" class="empty-state">
        <el-empty description="暂无假期余额记录" />
      </div>
      
      <el-table 
        v-else
        :data="balanceList" 
        style="width: 100%"
        stripe
        :empty-text="'暂无假期余额记录'"
      >
        <el-table-column v-if="isHR" label="员工" width="150" align="center">
          <template #default="scope">
            <span>{{ scope.row.userName || `员工${scope.row.userId}` }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年假余额" width="120" align="center">
          <template #default="scope">
            <span class="balance-text" :class="getBalanceClass(scope.row.annualBalance)">
              {{ formatBalance(scope.row.annualBalance) }}天
            </span>
          </template>
        </el-table-column>
        <el-table-column label="病假余额" width="120" align="center">
          <template #default="scope">
            <span class="balance-text" :class="getBalanceClass(scope.row.sickBalance)">
              {{ formatBalance(scope.row.sickBalance) }}天
            </span>
          </template>
        </el-table-column>
        <el-table-column label="事假余额" width="120" align="center">
          <template #default="scope">
            <span class="balance-text" :class="getBalanceClass(scope.row.personalBalance)">
              {{ formatBalance(scope.row.personalBalance) }}天
            </span>
          </template>
        </el-table-column>
        <el-table-column label="调休余额" width="120" align="center">
          <template #default="scope">
            <span class="balance-text" :class="getBalanceClass(scope.row.adjustmentBalance)">
              {{ formatBalance(scope.row.adjustmentBalance) }}天
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center">
          <template #default="scope">
            <span class="time-text">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="isHR" label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              size="small"
              @click="handleEditBalance(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              link 
              size="small"
              @click="handleIncreaseBalance(scope.row)"
            >
              增加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 设置/编辑余额弹窗 -->
    <el-dialog
      v-model="balanceDialogVisible"
      :title="isEdit ? '编辑假期余额' : '设置假期余额'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="balanceFormRef"
        :model="balanceForm"
        :rules="balanceRules"
        label-width="120px"
      >
        <el-form-item v-if="!isEdit" label="员工" prop="userId">
          <el-select
            v-model="balanceForm.userId"
            placeholder="请选择员工"
            filterable
            style="width: 100%"
            :loading="userListLoading"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="`${user.name || user.username} (${user.username})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-else label="员工">
          <el-input :value="currentEmployeeName" disabled />
        </el-form-item>
        <el-form-item label="年假余额" prop="annualBalance">
          <el-input-number
            v-model="balanceForm.annualBalance"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入年假余额"
          />
        </el-form-item>
        <el-form-item label="病假余额" prop="sickBalance">
          <el-input-number
            v-model="balanceForm.sickBalance"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入病假余额"
          />
        </el-form-item>
        <el-form-item label="事假余额" prop="personalBalance">
          <el-input-number
            v-model="balanceForm.personalBalance"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入事假余额"
          />
        </el-form-item>
        <el-form-item label="调休余额" prop="adjustmentBalance">
          <el-input-number
            v-model="balanceForm.adjustmentBalance"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入调休余额"
          />
        </el-form-item>
        <el-form-item label="备注" prop="reason">
          <el-input
            v-model="balanceForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="balanceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveBalance" :loading="saveLoading">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 增加余额弹窗 -->
    <el-dialog
      v-model="increaseDialogVisible"
      title="增加假期余额"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="increaseFormRef"
        :model="increaseForm"
        :rules="increaseRules"
        label-width="120px"
      >
        <el-form-item label="员工">
          <el-input :value="currentEmployeeName" disabled />
        </el-form-item>
        <el-form-item label="假期类型" prop="leaveType">
          <el-select v-model="increaseForm.leaveType" placeholder="请选择假期类型" style="width: 100%">
            <el-option label="年假" value="ANNUAL" />
            <el-option label="病假" value="SICK" />
            <el-option label="事假" value="PERSONAL" />
            <el-option label="调休" value="ADJUSTMENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="增加天数" prop="days">
          <el-input-number
            v-model="increaseForm.days"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入要增加的天数"
          />
        </el-form-item>
        <el-form-item label="原因" prop="reason">
          <el-input
            v-model="increaseForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入增加原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="increaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveIncrease" :loading="saveLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Calendar, Plus } from '@element-plus/icons-vue'

export default {
  name: 'LeaveBalance',
  components: {
    Calendar,
    Plus
  },
  setup() {
    const balanceList = ref([])
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const isHR = computed(() => userInfo.role === 'HR')
    const balanceDialogVisible = ref(false)
    const increaseDialogVisible = ref(false)
    const balanceFormRef = ref(null)
    const increaseFormRef = ref(null)
    const saveLoading = ref(false)
    const isEdit = ref(false)
    const currentBalance = ref(null)
    const userList = ref([])
    const userListLoading = ref(false)
    
    const balanceForm = ref({
      userId: null,
      annualBalance: 0,
      sickBalance: 0,
      personalBalance: 0,
      adjustmentBalance: 0,
      reason: ''
    })
    
    const increaseForm = ref({
      leaveType: 'ANNUAL',
      days: 0,
      reason: ''
    })
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    const formatBalance = (balance) => {
      if (balance === null || balance === undefined) return '0.0'
      return Number(balance).toFixed(1)
    }
    
    const getBalanceClass = (balance) => {
      const num = Number(balance) || 0
      if (num === 0) return 'balance-zero'
      if (num < 5) return 'balance-low'
      return 'balance-normal'
    }
    
    // 表单验证规则
    const balanceRules = {
      userId: [
        { required: true, message: '请选择员工', trigger: 'change' }
      ],
      annualBalance: [
        { type: 'number', min: 0, message: '年假余额不能为负数', trigger: 'blur' }
      ],
      sickBalance: [
        { type: 'number', min: 0, message: '病假余额不能为负数', trigger: 'blur' }
      ],
      personalBalance: [
        { type: 'number', min: 0, message: '事假余额不能为负数', trigger: 'blur' }
      ],
      adjustmentBalance: [
        { type: 'number', min: 0, message: '调休余额不能为负数', trigger: 'blur' }
      ]
    }
    
    const increaseRules = {
      leaveType: [
        { required: true, message: '请选择假期类型', trigger: 'change' }
      ],
      days: [
        { required: true, message: '请输入增加天数', trigger: 'blur' },
        { type: 'number', min: 0, message: '增加天数不能为负数', trigger: 'blur' }
      ],
      reason: [
        { required: true, message: '请输入增加原因', trigger: 'blur' }
      ]
    }
    
    // 当前员工名称（编辑时显示）
    const currentEmployeeName = computed(() => {
      if (!currentBalance.value) return ''
      return currentBalance.value.userName || `员工${currentBalance.value.userId}`
    })
    
    // 加载用户列表（用于新增时选择员工）
    const loadUserList = async () => {
      if (userList.value.length > 0) return // 已加载过
      try {
        userListLoading.value = true
        const res = await request.get('/user/list')
        if (res.code === 200 && res.data) {
          userList.value = res.data
        }
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      } finally {
        userListLoading.value = false
      }
    }
    
    // 打开编辑弹窗
    const handleEditBalance = (row) => {
      isEdit.value = true
      currentBalance.value = row
      balanceForm.value = {
        userId: row.userId,
        annualBalance: Number(row.annualBalance) || 0,
        sickBalance: Number(row.sickBalance) || 0,
        personalBalance: Number(row.personalBalance) || 0,
        adjustmentBalance: Number(row.adjustmentBalance) || 0,
        reason: ''
      }
      balanceDialogVisible.value = true
    }
    
    // 打开新增弹窗
    const handleAddBalance = async () => {
      isEdit.value = false
      currentBalance.value = null
      balanceForm.value = {
        userId: null,
        annualBalance: 0,
        sickBalance: 0,
        personalBalance: 0,
        adjustmentBalance: 0,
        reason: ''
      }
      await loadUserList()
      balanceDialogVisible.value = true
    }
    
    // 打开增加余额弹窗
    const handleIncreaseBalance = (row) => {
      currentBalance.value = row
      increaseForm.value = {
        leaveType: 'ANNUAL',
        days: 0,
        reason: ''
      }
      increaseDialogVisible.value = true
    }
    
    // 保存余额（新增或更新）
    const handleSaveBalance = async () => {
      if (!balanceFormRef.value) return
      
      try {
        await balanceFormRef.value.validate()
        saveLoading.value = true
        
        const data = {
          userId: balanceForm.value.userId,
          annualBalance: balanceForm.value.annualBalance,
          sickBalance: balanceForm.value.sickBalance,
          personalBalance: balanceForm.value.personalBalance,
          adjustmentBalance: balanceForm.value.adjustmentBalance,
          reason: balanceForm.value.reason || '手动设置'
        }
        
        const res = await request.post('/leave/balance/update', data)
        
        if (res.code === 200) {
          ElMessage.success('保存成功')
          balanceDialogVisible.value = false
          loadBalanceList() // 重新加载列表
        } else {
          ElMessage.error(res.message || '保存失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('保存失败')
        }
      } finally {
        saveLoading.value = false
      }
    }
    
    // 保存增加余额
    const handleSaveIncrease = async () => {
      if (!increaseFormRef.value) return
      
      try {
        await increaseFormRef.value.validate()
        saveLoading.value = true
        
        const data = {
          userId: currentBalance.value.userId,
          leaveType: increaseForm.value.leaveType,
          days: increaseForm.value.days,
          reason: increaseForm.value.reason
        }
        
        const res = await request.post('/leave/balance/increase', data)
        
        if (res.code === 200) {
          ElMessage.success('增加成功')
          increaseDialogVisible.value = false
          loadBalanceList() // 重新加载列表
        } else {
          ElMessage.error(res.message || '增加失败')
        }
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          ElMessage.error(error.response.data.message)
        } else {
          ElMessage.error('增加失败')
        }
      } finally {
        saveLoading.value = false
      }
    }
    
    const loadBalanceList = async () => {
      try {
        // HR角色查看所有余额，员工角色查看自己的余额
        const apiPath = isHR.value ? '/leave/balance/all' : '/leave/balance/my'
        const res = await request.get(apiPath)
        if (res.code === 200 && res.data) {
          // 如果是单个对象，转换为数组
          if (Array.isArray(res.data)) {
            balanceList.value = res.data
          } else {
            balanceList.value = [res.data]
          }
        } else {
          balanceList.value = []
        }
      } catch (error) {
        ElMessage.error('加载假期余额失败')
        balanceList.value = []
      }
    }
    
    onMounted(() => {
      loadBalanceList()
    })
    
    return {
      balanceList,
      isHR,
      formatDate,
      formatBalance,
      getBalanceClass,
      balanceDialogVisible,
      increaseDialogVisible,
      balanceForm,
      increaseForm,
      balanceFormRef,
      increaseFormRef,
      balanceRules,
      increaseRules,
      saveLoading,
      isEdit,
      currentBalance,
      currentEmployeeName,
      userList,
      userListLoading,
      handleAddBalance,
      handleEditBalance,
      handleIncreaseBalance,
      handleSaveBalance,
      handleSaveIncrease
    }
  }
}
</script>

<style scoped>
.leave-balance-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #409eff;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.balance-text {
  font-weight: 600;
  font-size: 16px;
}

.balance-text.balance-zero {
  color: #f56c6c;
}

.balance-text.balance-low {
  color: #e6a23c;
}

.balance-text.balance-normal {
  color: #67c23a;
}

.time-text {
  color: #666;
  font-size: 14px;
}

.empty-state {
  padding: 60px 0;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}
</style>

